<template>
  <div class="cover-container">
    <div class="cover-item" @click="showDialog">
      <img class="cover-image" :src="value" alt="">
    </div>
    <el-dialog title="上传封面" :visible.sync="dialogVisible" width="80%">
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="素材库" name="first">
          <ImageList :isShowAdd="false" :isShowCollected="false" :isShowSelected="false" ref="imageListRef"></ImageList>
        </el-tab-pane>
        <el-tab-pane label="上传图片" name="second">
          <div>
            <input type="file" ref="file" @change="uploadFile">
          </div>
          <img :src="imageUrl" alt="" style="width: 200px;height: 200px;">
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="uploadCover" :loading="loading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>s
<script>
  import {
    uploadImage
  } from '@/api/user.js'
  import ImageList from '@/components/image.vue'
  export default {
    name: 'Cover',
    props: ['value'],
    components: {
      ImageList
    },
    data() {
      return {
        dialogVisible: false,
        imageUrl: '',
        activeName: 'first',
        loading: false
      }
    },
    methods: {
      showDialog() {
        this.dialogVisible = true
      },
      uploadFile() {
        const file = this.$refs.file.files[0]
        const blob = window.URL.createObjectURL(file)
        this.imageUrl = blob
      },
      uploadCover() {
        if (this.activeName === 'first') {
          const imageList = this.$refs.imageListRef
          const selectedImage = imageList.selectedImage
          if (!selectedImage) {
            this.$message({
              type: 'error',
              message: '请选择文件!'
            })
            return
          }
          this.dialogVisible = false
          this.$emit('input', imageList.imagesList[selectedImage].url)
        }
        if (this.activeName === 'second') {
          const file = this.$refs.file.files[0]
          if (!file) {
            this.$message({
              type: 'error',
              message: '请选择文件!'
            })
            return
          }
          const formData = new FormData
          formData.append('image', file)
          this.loading = true
          uploadImage(formData).then(res => {
            this.loading = false
            this.dialogVisible = false
            this.$emit('input', res.data.data.url)
          })
        }
      }
    }
  }

</script>
<style lang="less" scoped>
  .cover-item {
    width: 150px;
    height: 150px;
    border: 1px dashed #d9d9d9;

    .cover-image {
      width: 100%;
      height: 100%;
    }
  }

</style>
